package Servlets.qy;

import Bean.*;
import Util.GokJDBCUtil2;
import Util.RES;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet(name = "StockOutServlet", urlPatterns = {"/StockOutServlet", "/pages/stock_manage/StockOutServlet"})
public class StockOutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    private void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Expires", "0");

        PrintWriter out = response.getWriter();
        String action = request.getParameter("action");

        try {
            switch (action) {
                case "getOrders":
                    getOrders(request, out);
                    break;
                case "getOrderDetails":
                    getOrderDetails(request, out);
                    break;
                case "completeOutbound":
                    completeOutbound(request, out);
                    break;
                case "cancelOutbound":
                    cancelOutbound(request, out);
                    break;
                case "deleteOutbound":
                    deleteOutbound(request, out);
                    break;
                default:
                    out.print(RES.fail("无效的操作"));
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("服务器内部错误: " + e.getMessage()));
        }
    }

    // 获取出库订单列表（带分页功能）
    private void getOrders(HttpServletRequest request, PrintWriter out) {
        try {
            String status = request.getParameter("status"); // "pending" or "completed"
            String orderCode = request.getParameter("orderCode"); // 订单号模糊查询参数
            String currentPageStr = request.getParameter("currentPage");
            String pageSizeStr = request.getParameter("pageSize");

            int currentPage = 1;
            int pageSize = 10;

            if (currentPageStr != null && !currentPageStr.isEmpty()) {
                currentPage = Integer.parseInt(currentPageStr);
            }

            if (pageSizeStr != null && !pageSizeStr.isEmpty()) {
                pageSize = Integer.parseInt(pageSizeStr);
            }

            String orderStatus = "0"; // 默认待发货

            if ("completed".equals(status)) {
                orderStatus = "1"; // 已发货
            }

            // 构建查询总数的SQL
            StringBuilder countSql = new StringBuilder();
            countSql.append("SELECT COUNT(*) FROM sales_order so ")
                    .append("LEFT JOIN user u ON so.userid = u.id ")
                    .append("WHERE so.orderstatus = ? AND so.isdeleted = 0 ");

            // 如果提供了订单号，则添加模糊查询条件
            if (orderCode != null && !orderCode.trim().isEmpty()) {
                countSql.append("AND so.code LIKE ? ");
            }

            // 获取总记录数
            int totalCount;
            if (orderCode != null && !orderCode.trim().isEmpty()) {
                totalCount = GokJDBCUtil2.queryForCount(countSql.toString(), orderStatus, "%" + orderCode + "%");
            } else {
                totalCount = GokJDBCUtil2.queryForCount(countSql.toString(), orderStatus);
            }

            int totalPage = (int) Math.ceil((double) totalCount / pageSize);

            // 计算偏移量
            int offset = (currentPage - 1) * pageSize;

            StringBuilder sql = new StringBuilder();
            sql.append("SELECT so.id, so.code, so.ordertime as orderTime, so.totalamount as totalAmount, ")
                    .append("so.orderstatus as orderStatus, so.paymentstatus as paymentStatus, u.username as userName ")
                    .append("FROM sales_order so ")
                    .append("LEFT JOIN user u ON so.userid = u.id ")
                    .append("WHERE so.orderstatus = ? AND so.isdeleted = 0 ");

            // 如果提供了订单号，则添加模糊查询条件
            if (orderCode != null && !orderCode.trim().isEmpty()) {
                sql.append("AND so.code LIKE ? ");
            }

            sql.append("ORDER BY so.ordertime DESC LIMIT " + offset + ", " + pageSize);

            List<StockSale> orders;
            if (orderCode != null && !orderCode.trim().isEmpty()) {
                // 有订单号查询条件
                orders = GokJDBCUtil2.queryAll(sql.toString(), StockSale.class, orderStatus, "%" + orderCode + "%");
            } else {
                // 无订单号查询条件
                orders = GokJDBCUtil2.queryAll(sql.toString(), StockSale.class, orderStatus);
            }

            // 构造返回结果
            StockMessage<StockSale> msg = new StockMessage<>(orders, String.valueOf(totalCount), String.valueOf(totalPage), String.valueOf(currentPage), String.valueOf(pageSize));

            out.print(RES.success(msg));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("获取出库订单失败"));
        }
    }

    // 获取订单详情
    private void getOrderDetails(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            // 查询订单详情，包含产品名称
            String sql = "SELECT sod.*, p.proname FROM sales_order_detail sod " +
                    "LEFT JOIN product p ON sod.proid = p.id " +
                    "WHERE sod.orderid = ? AND sod.isdeleted = 0";

            List<sales_order_detail> details = GokJDBCUtil2.queryAll(sql, sales_order_detail.class, orderId);
            out.print(RES.success(details));
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("获取订单详情失败"));
        }
    }

    // 完成出库（发货）
    private void completeOutbound(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            // 1. 检查订单是否已支付
            String checkPaymentSql = "SELECT * FROM sales_order WHERE id = ?";
            sales_order sorObject = GokJDBCUtil2.queryForObject(checkPaymentSql, sales_order.class, orderId);
            int paymentStatus = sorObject.getPaymentstatus();
            if (paymentStatus != 1) {
                out.print(RES.fail("订单未支付，无法发货"));
                return;
            }

            // 2. 更新订单状态为已发货
            String updateOrderSql = "UPDATE sales_order SET orderstatus = 1 WHERE id = ?";
            int orderResult = GokJDBCUtil2.update(updateOrderSql, orderId);

            if (orderResult <= 0) {
                out.print(RES.fail("订单不存在或已删除"));
                return;
            }
            // 3. 将该订单更新到income表中
            String insertIncomeSql = "INSERT INTO income (code, money, incometime, remark, createtime, updatetime) VALUES (?, ?, ?, ?, ?, ?)";
            String outcomeTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());

            String sql_saleorder = "SELECT * FROM sales_order WHERE id = ?";
            sales_order sor = GokJDBCUtil2.queryForObject(sql_saleorder, sales_order.class, orderId);
            String code = sor.getCode();
            String ordertime = sor.getOrdertime();
            String remark = sor.getRemark();
            BigDecimal totalamount = sor.getTotalamount();
            GokJDBCUtil2.update(insertIncomeSql, code, totalamount, ordertime, remark, outcomeTime, outcomeTime);

            // 4. 获取订单详情
            String detailSql = "SELECT * FROM sales_order_detail WHERE orderid = ? AND isdeleted = 0";
            List<sales_order_detail> details = GokJDBCUtil2.queryAll(detailSql, sales_order_detail.class, orderId);

            // 5. 更新产品库存（减少库存）
            for (sales_order_detail detail : details) {
                // 检查库存是否足够
                String checkStockSql = "SELECT quantity FROM product WHERE id = ?";
                Product prd = GokJDBCUtil2.queryForObject(checkStockSql, Product.class, detail.getProid());
                Integer currentStock = prd.getQuantity();
                if (currentStock == null || currentStock < detail.getProquantity()) {
                    out.print(RES.fail("产品库存不足，无法完成出库"));
                    return;
                }

                String updateProductSql = "UPDATE product SET quantity = quantity - ? WHERE id = ?";
                GokJDBCUtil2.update(updateProductSql, detail.getProquantity(), detail.getProid());
            }

            out.print(RES.success("发货成功"));
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("发货失败: " + e.getMessage()));
        }
    }

    // 取消出库
    private void cancelOutbound(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            String sql = "UPDATE sales_order SET orderstatus = 3 WHERE id = ?"; // 3表示已取消
            int result = GokJDBCUtil2.update(sql, orderId);

            if (result > 0) {
                out.print(RES.success("订单已取消"));
            } else {
                out.print(RES.fail("订单不存在或已删除"));
            }
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("取消订单失败"));
        }
    }

    // 删除出库订单（逻辑删除）
    private void deleteOutbound(HttpServletRequest request, PrintWriter out) {
        try {
            String orderIdStr = request.getParameter("orderId");
            if (orderIdStr == null || orderIdStr.isEmpty()) {
                out.print(RES.fail("订单ID不能为空"));
                return;
            }

            int orderId = Integer.parseInt(orderIdStr);

            // 逻辑删除订单和订单详情
            String updateOrderSql = "UPDATE sales_order SET isdeleted = 1 WHERE id = ?";
            String updateDetailSql = "UPDATE sales_order_detail SET isdeleted = 1 WHERE orderid = ?";

            GokJDBCUtil2.update(updateOrderSql, orderId);
            GokJDBCUtil2.update(updateDetailSql, orderId);

            out.print(RES.success("订单已删除"));
        } catch (NumberFormatException e) {
            out.print(RES.fail("订单ID格式错误"));
        } catch (Exception e) {
            e.printStackTrace();
            out.print(RES.fail("删除订单失败"));
        }
    }
}
